package com.qiangesoft.wechat.controller;

import com.qiangesoft.wechat.config.WxMpProperties;
import com.qiangesoft.wechat.dto.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * 微信用户控制器
 * ps:获取用户信息、授权网页用户信息等
 *
 * @author qiangesoft
 * @date 2023-09-11
 */
@Slf4j
@Api(tags = "微信用户")
@Controller
@RequestMapping("/wechat/user")
public class WxUserController {
    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    private WxMpService wxMpService;

    @ApiOperation(value = "个人信息")
    @GetMapping("/mine")
    public String mine() {
        WxOAuth2Service oAuth2Service = wxMpService.getOAuth2Service();
        // 构建授权url
        String authorizationUrl = oAuth2Service.buildAuthorizationUrl(wxMpProperties.getServer() + "wechat/user/callback", WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        return "redirect:" + authorizationUrl;
    }

    @ApiOperation(value = "个人信息网页授权回调")
    @GetMapping("/callback")
    public String callback(String code, Model model) throws WxErrorException {
        WxOAuth2UserInfo userInfo = this.getUserInfo(code);
        String openid = userInfo.getOpenid();

        // todo 通过openid拿取业务系统详细用户信息 IWxUserService

        UserDTO userDTO = new UserDTO();
        userDTO.setOpenId(openid);
        userDTO.setNickName(userInfo.getNickname());
        model.addAttribute("user", userDTO);
        return "mine";
    }

    /**
     * 获取微信用户信息
     *
     * @param code
     * @return
     * @throws WxErrorException
     */
    private WxOAuth2UserInfo getUserInfo(String code) throws WxErrorException {
        WxOAuth2Service oAuth2Service = wxMpService.getOAuth2Service();

        // 利用code获取accessToken
        WxOAuth2AccessToken accessToken = oAuth2Service.getAccessToken(code);

        // 利用accessToken获取用户信息
        WxOAuth2UserInfo userInfo = oAuth2Service.getUserInfo(accessToken, null);
        return userInfo;
    }
}
